<template>
  <Container class="coupon-list">
    <ManageSearchItem 
      v-show="tab === 'tab1'" 
      ref="aa" 
      slot="header" 
      :value="tab1SearchCondition" 
      :search-option="tab1SearchOption" 
      @onSearch="onSearch($event, 'tab1')" />
    <ReceiveSearchItem 
      v-show="tab === 'tab2'" 
      ref="bb" 
      slot="header" 
      :value="tab2SearchCondition" 
      :search-option="tab2SearchOption" 
      @onExport="onExport" 
      @onSearch="onSearch($event, 'tab2')" />
    <UseSearchItem 
      v-show="tab === 'tab3'" 
      :list='useList' 
      @onSearchBtnClick='getUseData' />
    <EditDialog @complete="getData" />
    <Tabs v-model="tab" @on-click="changeTab">
      <Button slot="extra" type="primary" size="large" icon="md-add" class="item" @click="onAddCoupon">新增优惠券</Button>
      <export-btn @onExport="onExport" class="item" slot="extra" v-if="tab === 'tab2'"></export-btn>
      <TabPane name="tab1" label="优惠券管理">
        <Table
          stripe
          :height="options.tableHeight"
          :columns="list.columns"
          :data="list.data"
          no-data-text="亲，没有找到相关记录哦！~"
        />
        <div class="pager">
          <Page
            :total="list.totalItem"
            :current="list.currentPage"
            :page-size="list.pageSize"
            show-sizer
            placement="top"
            @on-change="onPageChange"
            @on-page-size-change="onPageSizeChange"
          />
        </div>
        <Loader :status="list.status" @refresh="onSearchBtnClick" />
      </TabPane>
      <TabPane name="tab2" label="领券记录">
        <Table stripe :height="options.tableHeight" :columns="receiveList.columns" :data="receiveList.data" no-data-text="亲，没有找到相关记录哦！~" />
        <div class="pager">
          <Page
            :total="receiveList.totalItem"
            :current="receiveList.currentPage"
            :page-size="receiveList.pageSize"
            show-sizer
            placement="top"
            @on-change="onPageChange"
            @on-page-size-change="onPageSizeChange"
          />
        </div>
        <Loader :status="receiveList.status" @refresh="onSearchBtnClick" />
      </TabPane>
      <TabPane name="tab3" label="用券记录">
        <Table stripe :height="options.tableHeight" :columns="useList.columns" :data="useList.data" no-data-text="亲，没有找到相关记录哦！~" />
        <div class="pager">
          <Page
            :total="useList.totalItem"
            :current="useList.currentPage"
            :page-size="useList.pageSize"
            show-sizer
            placement="top"
            @on-change="onPageChange"
            @on-page-size-change="onPageSizeChange"
          />
        </div>
        <Loader :status="useList.status" @refresh="onSearchBtnClick" />
      </TabPane>
    </Tabs>
    <AddsumEditItem ref="addsumEdit" @complete="getData" />
    <Modal v-model="showEffectDialog" title="确认生效此优惠券？">
      <Form :label-width="80">
        <FormItem label="绑定条码: "><Input v-model="barcode" style="width: 100%" type="text" placeholder="请输入绑定条码" /></FormItem>
        <FormItem label="备注(选填): "><Input v-model="effectRemark" style="width: 100%" maxlength="200" type="textarea" placeholder="最多200字" /></FormItem>
      </Form>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="onCancelEffect">取消</Button>
        <Button type="primary" :disabled="btnDisabled" @click="onConfirmEffect">确定</Button>
      </div>
    </Modal>

    <Modal v-model="showInvalidDialog" title="确认作废此优惠券？">
      <div>备注(选填): <Input v-model="invalidRemark" style="width: 100%; margin-top: 10px" maxlength="200" type="textarea" placeholder="最多200字" /></div>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="onCancelInvalid">取消</Button>
        <Button type="primary" :disabled="btnDisabled" @click="onConfirmInvalid">确定</Button>
      </div>
    </Modal>
  </Container>
</template>
<script>
import { mapGetters } from 'vuex'
import { formatDate, clearEmpty } from '@/util'
import table from '@/table'
import listData from './list/CouponListData'
import receiveData from './list/CouponReceiveData'
import useData from './list/CouponUseData'
import EditDialog from './components/EditDialog'
import ManageSearchItem from './components/TableHeaderSearch'
import ReceiveSearchItem from './components/TableHeaderSearch'
import UseSearchItem from './components/TableHeaderUseSearch'
import AddsumEditItem from './list/AddsumEditItem'
export default {
  // name: 'sales/coupon/list',
  components: {
    EditDialog,
    ManageSearchItem,
    ReceiveSearchItem,
    UseSearchItem,
    AddsumEditItem
  },
  data () {
    return {
      list: listData,
      receiveList: receiveData,
      useList: useData,
      options: {
        tableHeight: 300
      },
      tab: this.$route.query.tab || 'tab1',
      tab1SearchOption: {
        showCouponName: {
          value: true,
          placeholder: '优惠券名称'
        },
        showDate: {
          value: true,
          placeholder: '请选择使用期限'
        }
      },
      searchCondition: {},
      tab1SearchCondition: {},
      tab2SearchCondition: {},
      tab2SearchOption: {
        showExport: false,
        showCouponId: {
          value: true,
          placeholder: '请输入优惠券名称'
        },
        showStoreName: {
          value: true
        },
        showSelect: {
          value: true,
          placeholder: '选择搜索的选项'
        },
        showStatus: {
          value: true
        },
        showDate: {
          value: true,
          placeholder: '选择日期'
        }
      },
      showEffectDialog: false,
      showInvalidDialog: false,
      couponId: this.$route.query.id,
      barcode: '', //绑定条码
      receiveId: '', //生效优惠券id
      effectRemark: '', //生效原因
      invalidRemark: '', //失效原因
      sendByQuantityRight: false, //发放条码方式权限
      sendByBarcodeRight: false, //发放条码方式权限,
      couponStatus: undefined
    }
  },
  computed: {
    ...mapGetters(['userMenu'])
  },
  watch: {
    $route (newVal) {
      this.tab = this.$route.query.tab || 'tab1'
      let page = ~~this.$route.query.currentPage
      let table1 = this.list
      let table2 = this.receiveList
      if (this.tab === 'tab1' && newVal.name === 'sales/coupon/list') {
        if (table1.currentPage !== page) {
          table1.currentPage = ~~this.$route.query.currentPage === 0 ? 1 : ~~this.$route.query.currentPage
          this.getData()
        }
      } else if (this.tab === 'tab2' && newVal.name === 'sales/coupon/list') {
        if (table2.currentPage !== page) {
          table2.currentPage = ~~this.$route.query.currentPage === 0 ? 1 : ~~this.$route.query.currentPage
          this.getData()
        }
      }
    }
  },
  created () {
    let data = {}
    Object.keys(this.$route.query).filter(key => key !== 'tab' && key !== 'pageSize' && key !== 'currentPage').forEach(key => {
      data[key] = this.$route.query[key]
    })
    this[`${this.tab}SearchCondition`] = data
  },
  mounted () {
    this.list.currentPage = ~~this.$route.query.currentPage || 1
    this.list.pageSize = ~~this.$route.query.pageSize || this.list.pageSize
    this.initTable()
    this.$bus.$on('onCopyCoupon', ({ item, index }) => this.onCopyCoupon(item, index))
    this.$bus.$on('onClose', ({ item, index }) => this.onClose(item, index))
    this.$bus.$on('onOpen', ({ item, index }) => this.onOpen(item, index))
    this.$bus.$on('onAddSum', this.onAddSum)
    this.$bus.$on('onEditGoods', this.onEditGoods)
    this.$bus.$on('statusSelect', data => {
      this.couponStatus = data[0] || undefined
      this.onSearchBtnClick()
    })
    this.$bus.$on('onEffect', (id) => {
      this.receiveId = id
      this.barcode = ''
      this.effectRemark = ''
      this.showEffectDialog = true
    })
    this.$bus.$on('onInvalid', (id) => {
      this.receiveId = id
      this.showInvalidDialog = true
    })
    this.userMenu.forEach(item => {
      if (item.viewUrl === '/sales/coupon/list/sendByQuantity') {
        this.sendByQuantityRight = item.hasRight
      } else if (item.viewUrl === '/sales/coupon/list/sendByBarcode') {
        this.sendByBarcodeRight = item.hasRight
      }
    })
    if (this.tab === 'tab1') {
      this.getData()
    }
  },
  destroyed () {
    this.$bus.$off()
  },
  beforeRouteLeave (to, from, next) {
    if (to.name === 'coupon/add') {
      sessionStorage.removeItem('couponForm')
      next()
    } else {
      next()
    }
  },
  methods: {
    ...table,
    onSearch (data, tab) {
      this.searchCondition = data
      this[`${tab}SearchCondition`] = data
      this.$router.replace({
        name: 'sales/coupon/list',
        query: {
          tab: this.tab,
          currentPage: this.tab === 'tab1' ? this.list.currentPage : this.receiveList.currentPage,
          pageSize: this.tab === 'tab1' ? this.list.pageSize : this.receiveList.pageSize,
          ...data
        }
      })
      this.onSearchBtnClick()
    },
    onSearchBtnClick () {
      this.list.currentPage = 1
      this.receiveList.currentPage = 1
      this.getData()
    },
    getData () {
      if (this.tab === 'tab1') {
        let param = {
          size: this.list.pageSize,
          current: this.list.currentPage
        }
        Object.keys(this.$route.query).filter(key => key !== 'tab' && key !== 'pageSize' && key !== 'currentPage').forEach(key => {
          if (key === 'startDate') {
            param.validityStartDate = formatDate(this.$route.query.startDate, true)
          } else if (key === 'endDate') {
            param.validityEndDate = formatDate(this.$route.query.endDate, true)
          } else {
            param[key] = this.$route.query[key]
          }
        })
        param.couponStatus = this.couponStatus
        this.list.status = 'loading'
        param = clearEmpty(param)
        this.$ajaxGet('/coupon/coupon_info/page', param).then(data => {
          data.records = data.records || []
          data.records.forEach(item => {
            item.sendByQuantityRight = this.sendByQuantityRight
            item.sendByBarcodeRight = this.sendByBarcodeRight
          })
          this.list.data = data.records
          this.list.totalItem = Number(data.total)
          this.backTableTop()
          this.list.status = 'pass'
        }).catch(() => {
          this.list.status = 'error'
        })
      } else if (this.tab === 'tab2') {
        let param = {
          size: this.receiveList.pageSize,
          current: this.receiveList.currentPage
        }
        Object.keys(this.searchCondition).forEach(key => {
          if (key === 'startDate') {
            param.beginReceiveDate = formatDate(this.searchCondition.startDate, true)
          } else if (key === 'endDate') {
            param.endReceiveDate = formatDate(this.searchCondition.endDate) + ' 23:59:59'
          } else {
            param[key] = this.searchCondition[key]
          }
        })
        this.receiveList.status = 'loading'
        param = clearEmpty(param)
        this.$ajaxGet('/coupon/coupon_receive/es_page', param).then(data => {
          if (data === 'NONE_QUERY_CONDITION') {
            this.receiveList.status = 'pass'
            this.receiveList.data = []
            this.$Message.warning({
              background: true,
              content: '请输入具体的查询条件'
            })
            return
          }
          data.records = data.records || []
          const statusMap = {
            PENDING_ACTIVATED: '待激活',
            USABLE: '可使用',
            USED: '已使用',
            INVALID: '已作废',
            OVERDUE: '已过期'
          }
          data.records.forEach(item => {
            item.statusStr = statusMap[item.status]
          })
          this.receiveList.data = data.records
          this.receiveList.totalItem = Number(data.total)
          this.backTableTop()
          this.receiveList.status = 'pass'
        }).catch((res) => {
          this.receiveList.status = 'error'
        })
      } else if ((this.tab === 'tab3')) {
        this.getUseData()
      }
    },
    getUseData () {
        let param = {
          size: this.useList.pageSize,
          current: this.useList.currentPage,
          useOrderSn: this.useList.form.orderSn
        }
        this.useList.status = 'loading'
        param = clearEmpty(param)
        this.$ajaxGet('/coupon/coupon_receive/used_page', param).then(data => {
          if (data === 'NONE_QUERY_CONDITION') {
            this.useList.status = 'pass'
            this.useList.data = []
            this.$Message.warning({
              background: true,
              content: '请输入具体的查询条件'
            })
            return
          }
          data.records = data.records || []
          const statusMap = {
            PENDING_ACTIVATED: '待激活',
            USABLE: '可使用',
            USED: '已使用',
            INVALID: '已作废',
            OVERDUE: '已过期'
          }
          data.records.forEach(item => {
            item.statusStr = statusMap[item.status]
          })
          this.useList.data = data.records
          this.useList.totalItem = Number(data.total)
          this.backTableTop()
          this.useList.status = 'pass'
        }).catch((res) => {
          this.useList.status = 'error'
        })
    },
    onAddSum (id) {
      this.$refs.addsumEdit.resetForm(id)
    },
    changeTab (name) {
      // this.$bus.$emit('resetSearch') //清空搜索条件
      this.$router.replace({
        name: 'sales/coupon/list',
        query: {
          tab: name,
          currentPage: this.tab === 'tab1' ? this.list.currentPage : this.receiveList.currentPage,
          pageSize: this.tab === 'tab1' ? this.list.pageSize : this.receiveList.pageSize,
          ...this[`${name}SearchCondition`]
        }
      })
      if (this.tab === 'tab1') {
        this.getData()
      }
    },
    onAddCoupon () {
      this.$router.push({
        name: 'coupon/add',
        query: {
          from: 'add'
        }
      })
    },
    onCopyCoupon (item, index) {
      this.$router.push({
        name: 'coupon/add',
        query: {
          id: item.id
        }
      })
    },
    onClose (row) {
      this.$Modal.confirm({
        title: '关闭',
        content: '优惠券关闭后不可重新启用，请谨慎操作',
        loading: true,
        onOk: () => {
          this.onChangeStatus(row)
          this.$Modal.remove()
        }
      })
    },
    onOpen (row) {
      this.$Modal.confirm({
        title: '确认',
        content: '确认启用？',
        loading: true,
        onOk: () => {
          this.onChangeStatus(row)
          this.$Modal.remove()
        }
      })
    },
    onChangeStatus (row) {
      let param = {
        couponId: row.id,
        couponStatusEnum: row.couponStatus === 'NO_OPEN' ? 'OPEN' : 'CLOSE'
      }
      this.$ajaxPost('/coupon/coupon_info/close', param).then(() => {
        this.$Notice.success({
          title: '操作成功'
        })
        this.getData()
      }).catch(() => {
        setTimeout(() => {
          this.$router.push({
            name: 'coupon/add',
            query: {
              id: row.id,
              type: 'open'
            }
          })
        }, 100)
      })
    },
    onPageChange (number) {
      if (this.tab === 'tab1') {
        this.list.currentPage = number
      } else {
        this.receiveList.currentPage = number
      }
      this.$router.push({
        name: 'sales/coupon/list',
        query: {
          currentPage: this.tab === 'tab1' ? this.list.currentPage : this.receiveList.currentPage,
          pageSize: this.tab === 'tab1' ? this.list.pageSize : this.receiveList.pageSize,
          tab: this.tab,
          ...this[`${this.tab}SearchCondition`]
        }
      })
      this.getData()
    },
    onPageSizeChange (pageSize) {
      this.$router.push({
        name: 'sales/coupon/list',
        query: {
          currentPage: 1,
          pageSize: this.tab === 'tab1' ? this.list.pageSize : this.receiveList.pageSize,
          tab: this.tab,
          ...this[`${this.tab}SearchCondition`]
        }
      })
      this.getData()
    },
    onConfirmInvalid () {
      const param = {
        receiveId: this.receiveId
      }
      if (this.invalidRemark) {
        param.remark = this.invalidRemark
      }
      this.$ajaxPost('/coupon/coupon_receive/to_invalid', param).then(res => {
        if (res) {
          this.$Notice.success({
            title: '操作成功'
          })
          this.showInvalidDialog = false
          this.getData()
        }
      })
    },
    onConfirmEffect () {
      const param = {
        receiveId: this.receiveId
      }
      if (this.barcode !== '') {
        param.barCode = this.barcode
      }
      if (this.effectRemark) {
        param.remark = this.effectRemark
      }
      this.$ajaxPost('/coupon/coupon_receive/to_activate', param).then(res => {
        if (res) {
          this.barcode = ''
          this.$Notice.success({
            title: '操作成功'
          })
          this.showEffectDialog = false
          this.getData()
        }
      })
    },
    onExport (data) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定导出列表?',
        onOk: () => {
          this.searchCondition = this.$refs.bb.handleSearchCondition()
          let param = {
            size: this.receiveList.pageSize,
            current: this.receiveList.currentPage
          }
          Object.keys(this.searchCondition).forEach(key => {
            if (key === 'startDate') {
              param.beginReceiveDate = formatDate(this.searchCondition.startDate, true)
            } else if (key === 'endDate') {
              param.endReceiveDate = formatDate(this.searchCondition.endDate) + ' 23:59:59'
            } else {
              param[key] = this.searchCondition[key]
            }
          })
          param = clearEmpty(param)
          this.$ajaxPost('/coupon/coupon_receive/coupon_receive_export', param).then(res => {
            if (res === 'NONE_QUERY_CONDITION') {
              this.$Message.warning({
                background: true,
                content: '请输入具体的查询条件'
              })
            } else {
              this.$router.push('/home/export/list')
            }
          })
        }
      })
    },
    onCancelEffect () {
      this.showEffectDialog = false
    },
    onCancelInvalid () {
      this.showInvalidDialog = false
    },
    onEditGoods (id) {
      this.$router.push({ name: 'sales/coupon/select', query: { couponId: id, type: 'editgood' } })
    }
  }

}
</script>
